package com.myapp.sqlmapper;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.myapp.util.CommUtil;

public class SQLUtil {
	private String getThisPath() {
		return this.getClass().getResource("").getPath();
	}

	/**
	 * 读取XML中的SQL语句
	 * */
	public static String getSql(String fileName, List<String> paramList) {
		if (fileName == null) {
			System.out.println("SQL文件路径为空");
			return null;
		}
		if (fileName.split("\\.").length != 2) {
			System.out.println("SQL文件路径不合法");
			return null;
		}
		String sqlFileName = fileName.split("\\.")[0];
		String sqlMethodName = fileName.split("\\.")[1];
		if (CommUtil.isBlank(sqlMethodName) || CommUtil.isBlank(sqlFileName)) {
			System.out.println("SQL文件路径不合法");
			return null;
		}
		String sql = "";
		SQLUtil sqlutil = new SQLUtil();
		String rootFileName = sqlutil.getThisPath();
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(new File(rootFileName
					+ File.separator + sqlFileName + ".xml"));
			Element root = document.getRootElement();
			Element foo;
			for (Iterator i = root.elementIterator("VALUE"); i.hasNext();) {
				foo = (Element) i.next();
				if (foo.attributeValue("id") != null
						&& foo.attributeValue("id").equals(sqlMethodName)) {
					sql = foo.elementText("sql");
					System.out.println("原始sql:" + sql);
					if (sql.contains("?")) {
						int count = CommUtil.countMatches(sql, "?");
						if (count != paramList.size()) {
							System.out.println("参数个数与SQL中参数个数不一致");
							return null;
						} else {
							for (int j = 0; j < count; j++) {
								sql = sql.replaceFirst("\\?", paramList.get(j)==null?"null":paramList.get(j));
							}
						}
					}
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(fileName + "从XML文件读取并替换后的SQL：" + sql);
		return sql;
	}

	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("nickname");
		list.add("machineid");
		getSql("userMapper.insertUser", list);
	}
}
